import { Button, Table } from 'antd';
import axios from 'axios';
import React, { useEffect, useState, useMemo, useRef } from 'react';
import dayjs from 'dayjs';
import { useRouter, withRouter } from 'next/router';
import PageTitle from '@/components/pageTitle';
import { colWidth, getQueryString } from '@/utils/tools';
import { searchApi } from '@/request/gitlab';
import { useHeight } from '@/utils/hooks/height';
import ProjectSearch from './search';

interface Project {
  id: number | string;
  namespace: {
    name: string;
  };
  name: string;
  branch: string;
  default_branch: string;
}
const Index = () => {
  const [searchParams, setSearchParams] = useState<any>(null);
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { height } = useHeight(320);
  const firstUpdate = useRef(true);

  const handleDiff = async (record: { branch: string; id: string }) => {
    const { branch, id } = record;
    const res: any = await searchApi({ id });
    const result: Project = res[0];
    const link = `https://gitlab.jrdaimao.com/${result.namespace.name}/${result.name}/-/compare/${branch}...${result.default_branch}?from_project_id=${result.id}`;
    window.open(link);
  };

  const handleProject = async (record: { id: string }) => {
    const { id } = record;
    const res = await axios.post('/api/gitlab/search', { id });
    const result: Project = res.data.data[0];
    const link = `https://gitlab.jrdaimao.com/${result.namespace.name}/${result.name}`;
    window.open(link);
  };

  const handleBranch = async (record: { branch: string; id: string }) => {
    const { branch, id } = record;
    const res = await axios.post('/api/gitlab/search', { id });
    const result: Project = res.data.data[0];
    const link = `https://gitlab.jrdaimao.com/${result.namespace.name}/${result.name}/-/tree/${branch}`;
    window.open(link);
  };

  const columns: any = useMemo(
    () => [
      {
        title: '项目名称',
        dataIndex: 'name',
        width: 200,
        showSorterTooltip: false,
        sorter: (a, b) => a.name.localeCompare(b.name),
        render: (text, record: any) => (
          <a
            onClick={() => {
              handleProject(record);
            }}
            className="tableTitle"
          >
            {text}
          </a>
        ),
      },
      {
        title: '项目分支',
        dataIndex: 'branch',
        width: 300,
        showSorterTooltip: false,
        sorter: (a, b) => a.branch.localeCompare(b.branch),
        render: (text, record: any) => (
          <a
            onClick={() => {
              handleBranch(record);
            }}
            className="tableTitle"
          >
            {text}
          </a>
        ),
      },
      {
        title: '提交人员',
        dataIndex: 'author',
        width: 150,
        showSorterTooltip: false,
        sorter: (a, b) => a.author.localeCompare(b.author),
      },
      {
        title: '消息内容',
        dataIndex: 'message',
        width: 300,
      },
      {
        title: '提交时间',
        dataIndex: 'commitDate',
        width: 220,
      },
      {
        title: '统计时间',
        dataIndex: 'createAt',
        width: 150,
        render: (text) => dayjs(text).format('YYYY-MM-DD HH'),
      },
      {
        title: '操作',
        fixed: 'right',
        width: 150,
        render(text, record) {
          return (
            <div>
              <Button
                type="primary"
                onClick={() => {
                  handleDiff(record);
                }}
              >
                diff分支地址
              </Button>
            </div>
          );
        },
      },
    ],
    [],
  );

  const handleSearch = async (params) => {
    setLoading(true);
    try {
      const ret = await axios.post('/api/func/getMergeLog', { ...params, pageSize: 100 });
      setList(ret.data.data);
    } catch (err: any) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const handleFinish = (value: any) => {
    setSearchParams(value);
  };

  const handleReset = () => {
    setSearchParams({});
  };

  useEffect(() => {
    const author = getQueryString('name');
    if (author) {
      setSearchParams({
        author,
      });
    } else {
      handleSearch(searchParams);
    }
  }, []);

  useEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }
    if (searchParams === null) {
      handleSearch({ createAt: dayjs().format('YYYY-MM-DD') });
      return;
    }
    handleSearch(searchParams);
  }, [searchParams]);

  return (
    <div>
      <PageTitle title="未合并主分支记录" />
      <ProjectSearch handleFinish={handleFinish} handleReset={handleReset} />
      <Table columns={columns} pagination={false} dataSource={list} rowKey="_id" scroll={{ x: colWidth(columns), y: height }} loading={loading}></Table>
    </div>
  );
};

export default withRouter(Index);
